package com.id.sigma.camel;

import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Exchange;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.id.sigma.ManageBrokeSingleton;

public class CamelMain {
	public static void main(String[] args) {
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				try {
//					fromUi();
//				} catch (ParseException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}).start();
//		
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				fromCore();
//			}
//		}).start();
		try {
			fromUi();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		fromCore();
	}
	
	public static void fromUi() throws ParseException{
		System.out.println("nunggu dari ui");
		while (true){
			
			ApplicationContext context = new ClassPathXmlApplicationContext(
					"CamelBeans.xml");
			ConsumerTemplate cTemplate = context.getBean("camelConsumer",
					ConsumerTemplate.class);
			Exchange ex = cTemplate.receive("jms:queue:Azis");
			String message = (String) ex.getIn().getBody();
			System.out.println(message);
			JSONParser parser = new JSONParser();
			
			JSONObject jObject = (JSONObject)parser.parse(message);
			String methode =  (String)jObject.get("methode");
			try {
				String kirimPesan="";
				if (methode.equals("select")) {
					kirimPesan = ManageBrokeSingleton.getInstance().getBroker((String)jObject.get("id"));
				}else if (methode.equals("input")) {
					kirimPesan = ManageBrokeSingleton.getInstance().addBroker( (String)jObject.get("nama"),
							(String)jObject.get("alamat"), (Long)jObject.get("saldoUang"), (Long)jObject.get("saldoSaham"));
				}else if (methode.equals("update")) {
					kirimPesan = ManageBrokeSingleton.getInstance().updateBrokers((String)jObject.get("id"), (String)jObject.get("nama"),
							(String)jObject.get("alamat"), (Long)jObject.get("saldoUang"), (Long)jObject.get("saldoSaham"));
				}else if (methode.equals("delete")) {
					kirimPesan = ManageBrokeSingleton.getInstance().deleteBroker((String)jObject.get("id"));
				}else if (methode.equals("selectAll")){
					kirimPesan = ManageBrokeSingleton.getInstance().listBrokers();
				}		
				CamelService.getInstance().sendToActiveMq(kirimPesan, "jms:queue:Misbah");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
		}
			
	}
	
	public static void fromCore(){
		System.out.println("nunggu dari core");
//		while(true){
			
//		}
	}
}
